package org.zetaframework.job;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zetaframework.job.properties.JobProperties;

/**
 * XxlJob 配置类
 *
 * @author gcc
 */
@Configuration
@EnableConfigurationProperties(JobProperties.class)
public class XxlJobConfig {
    private static final Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    private final JobProperties jobProperties;
    public XxlJobConfig(JobProperties jobProperties) {
        this.jobProperties = jobProperties;
    }

    /**
     * 配置 xxl-job spring执行器
     *
     * @return XxlJobSpringExecutor
     */
    @Bean
    public XxlJobSpringExecutor xxlJobSpringExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        JobProperties.Admin admin = jobProperties.getAdmin();
        JobProperties.Executor executor = jobProperties.getExecutor();

        XxlJobSpringExecutor jobExecutor = new XxlJobSpringExecutor();
        // xxl-job 调度中心配置 相关配置
        jobExecutor.setAdminAddresses(admin.getAddresses());
        jobExecutor.setAccessToken(admin.getAccessToken());
        jobExecutor.setTimeout(admin.getTimeout());
        // xxl-job 执行器 相关配置
        jobExecutor.setAppname(executor.getAppName());
        jobExecutor.setIp(executor.getIp());
        jobExecutor.setPort(executor.getPort());
        jobExecutor.setLogPath(executor.getLogPath());
        jobExecutor.setLogRetentionDays(executor.getLogRetentionDays());
        return jobExecutor;
    }

    /**
     * 针对多网卡、容器内部署等情况，可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP；
     *
     *      1、引入依赖：
     *          <dependency>
     *             <groupId>org.springframework.cloud</groupId>
     *             <artifactId>spring-cloud-commons</artifactId>
     *             <version>${version}</version>
     *         </dependency>
     *
     *      2、配置文件，或者容器启动变量
     *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
     *
     *      3、获取IP
     *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
     */

}
